package com.Hsu.blog.config;

import com.Hsu.blog.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author Hsu琛君珩
 * @ClassName:LoginInterceptor
 * @date 2024-01-25
 * @apiNote
 * @Version: v1.0
 */

@Slf4j
@Configuration
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //进行用户登录校验
        //1.从header中获取token
        String token=request.getHeader("user_token");
        //约定前端发送请求时，header的这个key是 user_token
        //这个 user_token 和前端存储的 user_token 只是名称一样，之间没有关系
        log.info("从header中获取token，token："+token);
        //2.验证token
        Claims claims= JwtUtils.parseToken(token);
        if(claims==null){
            //token是不合法的
            response.setStatus(401);//表示需要登录
            return false;//进行拦截
        }
        return true;
    }
}

